<template>
  <div ref="read" v-loading="loading || !canShowSetting" class="read">
    <div class="read-head">
      <div class="read-head-left">
        <div class="left-title">
          <fks-input
            v-model="current_content.title"
            size="large"
            maxlength="50"
            :placeholder="LANG.INPUT_TITLE"
          />
          <span style="margin-right: 24px; margin-left: auto">
            <!-- <span>{{ current_content.createBy }}</span>
            <span>{{ current_content.createDate }}</span> -->
          </span>
        </div>
      </div>
      <div class="read-head-right">
        <div class="right-title">
          <fks-button icon="fks-icon-setting" @click="changeShowSetting">
            {{ LANG.SETTING }}
          </fks-button>
          <fks-button icon="fks-icon-upload" @click="save('storage')">
            {{ LANG.CONTENT_STORAGE }}
          </fks-button>
          <fks-button
            icon="fks-icon-check"
            type="primary"
            @click="save('submit')"
          >
            {{ LANG.SUBMIT }}
          </fks-button>
        </div>
      </div>
    </div>

    <div class="body-container">
      <div :class="show_setting ? 'read-body-open' : 'read-body-close'">
        <Editor ref="Editor" v-model="current_content.context" />
      </div>
      <fks-collapse-transition>
        <div v-if="canShowSetting" v-show="show_setting" class="read-setting">
          <add-detail
            ref="detailTable"
            :visible="true"
            :operate-type="'edit'"
            :current-content="current_content"
            :template-detail="template_detail"
            :current-content-details="current_content_details"
            @success="onSuccess($event)"
            @quit="quit"
          />
        </div>
      </fks-collapse-transition>
    </div>
  </div>
</template>

<script>
import { addContent, updateContent } from './api/index'
import {
  getContentById,
  findFieldByName,
  getContentDetail,
  getContentStatus,
  addContentStatus,
  getTemplateDetailById,
  getCategoryById,
  getLastPublish,
  updateContentStatus
} from '@/modules/Content/api'
import Editor from '@/components/Editor/index'
import AddDetail from './components/AddDetail/index'
import * as actionTypes from '@/store/Action/actionTypes'
import { VISITED_VIEWS } from '@/store/State/stateTypes'
import mix from '@/mixins/module'

export default {
  name: 'ContentEditor',
  components: { Editor, AddDetail },
  mixins: [mix],
  data() {
    return {
      contentId: '',
      categoryId: '',
      loadingCount: 0,
      loading: true,
      canShowSetting: false,
      timer: null,
      timeWait: 2000,
      contentStatus: null,
      newContent: null,
      current_content: {},
      current_content_details: [],
      template_detail: [],
      fileList: [],
      communications: [],
      revisionsList: [], //历史版本列表
      showFiles: [], //fileList过滤之后的文件
      fileFlag: '正文附件',
      title: '',
      comm_input: '',
      drawer: false,
      input_status: false,
      show_setting: false,
      edit_flag: false,
      isEdit: false,
      downloadFlag: true,
      pre_view_file_control: false,
      edit_control: false,
      current_file: {}
    }
  },
  computed: {
    visitedViews() {
      return this.$store.state[VISITED_VIEWS]
    },
    input_row() {
      if (this.input_status) {
        return 5
      } else {
        return 1
      }
    }
  },
  watch: {
    $route: function () {
      this.initQuery()
    }
  },
  created() {},
  mounted() {
    this.initQuery()
  },
  beforeDestroy() {},
  methods: {
    /**
     * @description: 弹出的方法
     */
    quit() {
      setTimeout(() => {
        this.loading = false
        // updateES()
        this.closeSelectedTag()
        this.$router.push({
          name: 'contentList'
        })
      }, 500)
    },

    /**
     * @description:提交/暂存后删除标签
     */
    closeSelectedTag() {
      for (let i = 0; i < this.visitedViews.length; i++) {
        if (this.visitedViews[i].activePath == this.$route.path) {
          this.$store.dispatch(actionTypes.DEL_VIEW, this.visitedViews[i])
          break
        }
      }
    },

    changeStatusToAUDIT() {
      let temp
      if (this.contentStatus != 'DRAFT') {
        temp = [
          {
            status: 'DRAFT',
            contentId: this.contentId
          },
          {
            status: 'AUDIT',
            contentId: this.contentId
          }
        ]
      } else {
        temp = [
          {
            status: 'AUDIT',
            contentId: this.contentId
          }
        ]
      }

      return addContentStatus(temp)
    },

    /**
     * @description: 新建内容时，提交内容
     */
    createContent() {
      let data = this.current_content
      return addContent(data)
        .then((res) => {
          if (res.status) {
            this.current_content.id = res.data ? res.data : ''
            this.contentId = res.data ? res.data : ''
          }
        })
        .catch(() => {})
    },

    save(type) {
      if (this.current_content.title == '' || !this.current_content.title) {
        this.$message.error(this.LANG.TITLE_NOT_EMPTY)
        return
      }
      if (this.contentStatus == 'REVOKE') {
        this.delLastPublish(type)
      } else {
        this.saveHandler(type)
      }
    },

    saveHandler(type) {
      if (type == 'submit') {
        this.submit()
      }
      if (type == 'storage') {
        this.storage()
      }
    },

    /**
     * @description: 当存在将要到来的发布时，取消它
     */
    delLastPublish(type) {
      let now = this.$dayjs().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
      getLastPublish(this.contentId)
        .then((res) => {
          if (res.status) {
            let length = res.data.length
            if (length > 0) {
              for (let i = 0; i < length; i++) {
                let item = res.data[i]
                if (item.status == 'PUBLISH') {
                  let temp = item
                  temp.startTime = now
                  temp.deleteFlag = -1
                  temp.endTime = now
                  updateContentStatus(temp)
                    .then((res) => {
                      if (res.status) {
                        setTimeout(() => {
                          this.saveHandler(type)
                        }, 500)
                      }
                    })
                    .catch(() => {})
                }
                /**
                 * @description: 被撤下的内容有置顶状态，直接删除置顶状态信息
                 */
                if (item.status == 'TOP') {
                  let temp = item
                  temp.deleteFlag = -1
                  updateContentStatus(temp)
                }
              }
            } else {
              this.saveHandler(type)
            }
          }
        })
        .catch(() => {})
    },

    storage: async function () {
      this.loading = true
      let temp = [
        {
          status: 'DRAFT',
          contentId: this.contentId
        }
      ]
      if (this.contentStatus == 'NEW') {
        await this.createContent()
        temp[0].contentId = this.contentId
        addContentStatus(temp)
          .then((res) => {
            if (res.status) {
              this.$refs.detailTable.create()
            }
          })
          .catch(() => {})
        return
      }
      if (this.contentStatus != 'DRAFT') {
        addContentStatus(temp)
          .then((res) => {
            if (res.status) {
              this.$refs.detailTable.update()
            }
          })
          .catch(() => {})
      } else {
        this.$refs.detailTable.update()
      }
    },

    /**
     * @description:提交文章，状态变为审核中
     */
    submit: async function () {
      this.loading = true
      if (this.contentStatus == 'NEW') {
        await this.createContent()
        this.changeStatusToAUDIT()
          .then((res) => {
            if (res.status) {
              this.$refs.detailTable.create()
            }
          })
          .catch(() => {})
        return
      }
      this.changeStatusToAUDIT()
        .then((res) => {
          if (res.status) {
            this.$refs.detailTable.update()
          }
        })
        .catch(() => {})
    },

    onSuccess() {
      let data = this.current_content
      this.updateContent(data)
    },

    /**
     * @description: 更新内容基本信息
     */
    updateContent(temp) {
      return updateContent(temp)
        .then((res) => {
          if (res.status) {
            // this.initData()
            if (this.contentStatus == 'NEW') {
              this.$message.success(this.LANG.ADD_SUCCESS)
            } else {
              this.$message.success(this.LANG.EDIT_SUCCESS)
            }
            this.quit()
          }
        })
        .catch(() => {})
    },

    changeShowSetting() {
      this.show_setting = !this.show_setting
    },
    afterLoad() {
      this.loadingCount++
      if (this.loadingCount >= 2) {
        if (this.template_detail.length > 5) {
          this.changeShowSetting()
        }
        this.canShowSetting = true
      }
    },

    /**
     * @description: 获取内容的Status,没有status就弹出
     */
    getStatus() {
      getContentStatus(this.contentId)
        .then((res) => {
          if (res.status) {
            this.contentStatus = res.data
            this.edit_flag =
              res.data == 'DRAFT' ||
              res.data == 'FAILURE' ||
              res.data == 'REVOKE'
                ? true
                : false
            if (!this.edit_flag) {
              this.$message.error(this.LANG.ERROR_CANNOT_EDIT)
              this.quit()
              return
            }
            this.getContent()
            this.getDetailListById()
            this.$message({
              message: this.LANG.EDIT_WARN,
              type: 'warning'
            })
          } else {
            this.$message.error(this.LANG.ERROR_PATH_PARAM)
            this.quit()
            return
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 存在contentID时获取内容相关
     */
    getContent() {
      getContentById(this.contentId)
        .then((res) => {
          if (res.data) {
            let content = JSON.parse(JSON.stringify(res.data))
            this.current_content = content
            this.categoryId = content.categoryId
            this.getCategory()
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 获得分类目录及它的模板信息
     */
    getCategory() {
      getCategoryById(this.categoryId)
        .then((res) => {
          if (res.data.length > 0) {
            getTemplateDetailById(res.data[0].templateId)
              .then((res) => {
                this.template_detail = res.data
                this.afterLoad()
              })
              .catch(() => {})
          } else {
            this.$message.error(this.LANG.ERROR_PATH_PARAM)
            this.quit()
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 根据内容id获得它的详情列表
     */
    getDetailListById() {
      let temp = {
        contentId: this.contentId,
        page: 1,
        size: 150
      }
      getContentDetail(temp)
        .then((res) => {
          if (res.status) {
            this.current_content_details = res.data
            this.afterLoad()
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 根据name获取可变字段
     */
    findFieldByName(name) {
      return findFieldByName(name, this.current_content_details)
    },

    setArticleContent(content) {
      this.$refs.ARTICLE.append(content)
    },

    /**
     * @description: 初始化
     */
    clearData() {
      this.loadingCount = 0
      this.canShowSetting = false
      this.loading = true
    },
    initContent() {
      this.current_content = {
        title: this.LANG.NEW_CONTENT,
        categoryId: this.categoryId
      }
    },
    initData() {
      this.clearData()
      if (this.categoryId) {
        this.contentStatus = 'NEW'
        this.afterLoad()
        this.loading = false
        this.initContent()
        this.getCategory()
        return
      }
      if (this.contentId) {
        this.getStatus()
        return
      }
    },

    initQuery() {
      this.contentId = this.$route.query.ContentId
      this.categoryId = this.$route.query.CategoryId
      if (!(this.contentId || this.categoryId)) {
        this.$message.error(this.LANG.ERROR_PATH_PARAM)
        this.quit()
        return
      }
      this.initData()
    }
  }
}
</script>

<style scoped lang="scss">
@import 'asset/style/read';
</style>